local DIY = require "packages.diy_utility.diy_utility"

local skel = fk.CreateSkill{
  name = "sj7__yulie",
  tags = { Skill.Switch },
}

Fk:loadTranslationTable{
  ["sj7__yulie"] = "欲烈",
  [":sj7__yulie"] = "<b>转换技</b>，你可以: <br>"..
"①使用【杀】后，视为使用一张【火攻】；<br>"..
"②弃牌后，视为使用一张明牌<a href=':sanshe__foresight'>【洞烛先机】</a>；<br>"..
"③出牌阶段，重铸<a href='zhongyangqu_js'>中央区</a>的【杀】。<br>"..
"上述流程出现【闪】后，你移除该项。",

  ["#sj7__yulie_wake"] = "<b>转换技</b>，你可以: <br>"..
"①“<a href=':qice'>奇策</a>”；"..
"②“<a href=':zaiqi'>再起</a>”；"..
"③“<a href=':zhiheng'>制衡</a>”。<br>"..
"上述流程出现【闪】后，你移除该项。",

  ["#sj7__yulie-recast"] = "欲烈：你可以重铸中央区的【杀】",

  ["$RecastCenterArea"] = "%from 因 “%arg” 重铸了中央区的 %card",

  ["$sj7__yulie1"] = "",
  ["$sj7__yulie2"] = "",
}
skel.dynamicDesc = function (self, player, lang)
  return player:getMark(skel.name.."_wake") == 0 and Fk:translate(":sj7__yulie") or Fk:translate("#sj7__yulie_wake")
end

local remove = function (player,ids,n)
  if table.find(ids,function (id)
    return Fk:getCardById(id).trueName == "jink"
  end) then
    player.room:addTableMarkIfNeed(player,skel.name.."_t",n)
  end
  if #player:getTableMark(skel.name.."_t") == 3 then
    if player:getMark(skel.name.."_wake") == 0 and player:hasSkill("sj7__wenjue") then
      local wenjue = Fk.skills["sj7__wenjue"]
      player.room:useSkill(player,wenjue,function ()
        DIY.setSwitchState(player, skel.name, 1, 3)
        player.room:setPlayerMark(player,skel.name.."_t",0)
        player.room:setPlayerMark(player,skel.name.."_wake",1)
      end)
    else
      DIY.removeSwitchSkill(player, skel.name)
    end
  end
end

local change = function (player)
  repeat
    DIY.changeSwitchState(player,skel.name)
    local mark = player:getTableMark(skel.name.."_t")
  until not table.contains(mark,DIY.getSwitchState(player,skel.name)) or #mark > 2
end

skel:addEffect(fk.CardUseFinished, {
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(skel.name) and data.card.trueName == "slash"
    and DIY.getSwitchState(player,skel.name) == 1 and player:getMark(skel.name.."_wake") == 0
  end,
  on_cost = function (self, event, target, player, data)
    local use = player.room:askToUseVirtualCard(player,{
      name = "fire_attack",
      skill_name = skel.name,
      skip = true,
    })
    event:setCostData(self,{use = use})
    return use
  end,
  on_use = function(self, event, target, player, data)
    change(player)
    player.room:useCard(event:getCostData(self).use)
  end,
})

skel:addEffect(fk.AfterCardsMove, {
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(skel.name) and DIY.getSwitchState(player,skel.name) == 2 and player:getMark(skel.name.."_wake") == 0 then
      for _, move in ipairs(data) do
        return move.moveReason == fk.ReasonDiscard and move.from and move.from == player and move.proposer and move.proposer == player
      end
    end
  end,
  on_cost = function (self, event, target, player, data)
    local use = player.room:askToUseVirtualCard(player,{
      name = "sanshe__foresight",
      skill_name = skel.name,
      skip = true,
    })
    event:setCostData(self,{use = use})
    return use
  end,
  on_use = function(self, event, target, player, data)
    local use = event:getCostData(self).use
    change(player)
    use.extra_data = use.extra_data or {}
    use.extra_data.show = true  --明牌
    use.extra_data.afterfun = function (effect)
      remove(player,effect.extra_data.see,2)
    end
    player.room:useCard(use)
  end,
})

skel:addEffect("active", {
  prompt = function (self, player, selected_cards, selected_targets)
    if player:getMark(skel.name.."_wake") > 0 then
      if DIY.getSwitchState(player,skel.name) == 1 then
        return "#qice"
      else
        return "#zhiheng-active"
      end
    end
    return "#sj7__yulie-recast"
  end,
  target_num = 0,
  can_use = function(self, player)
    local n = DIY.getSwitchState(player,skel.name)
    if player:getMark(skel.name.."_wake") == 0 then
        return n == 3 and table.find(DIY.getCenterCards(Fk:currentRoom()),function (id)
          return Fk:getCardById(id).trueName == "slash"
        end)
    else
      if n == 3 then
        return player:usedSkillTimes("zhiheng", Player.HistoryPhase) == 0 and 
          table.find(player:getCardIds("he"),function (id)
            return not player:prohibitDiscard(id)
          end)
      elseif n == 1 then
        return player:usedSkillTimes("qice", Player.HistoryPhase) == 0 and not player:isKongcheng()
        and #player:getViewAsCardNames("qice", Fk:getAllCardNames("t"), player:getCardIds("h")) > 0
      end
    end
  end,
  card_filter = function (self, player, to_select, selected)
    if player:getMark(skel.name.."_wake") > 0 and DIY.getSwitchState(player,skel.name) == 3 then
      return not player:prohibitDiscard(to_select)
    end
    return false
  end,
  feasible = function (self, player, selected, selected_cards, card)
    if player:getMark(skel.name.."_wake") > 0 and DIY.getSwitchState(player,skel.name) == 3 then
      return #selected_cards > 0
    end
    return true
  end,
  on_use = function(self, room, effect)
    local player = effect.from
    local n = DIY.getSwitchState(player,skel.name)
    change(player)
    local ids
    if player:getMark(skel.name.."_wake") > 0 then
      if n == 3 then
        player:addSkillUseHistory("zhiheng")
        ids = effect.cards
        remove(player,ids,3)
        room:throwCard(ids, "zhiheng", player, player)
        if player:isAlive() then
          player:drawCards(#ids, "zhiheng")
        end
      elseif n == 1 then
        player:addSkillUseHistory("qice")
        ids = player:getCardIds("h")
        remove(player,ids,1)
        room:askToUseVirtualCard(player,{
          name = player:getViewAsCardNames("qice", Fk:getAllCardNames("t"), ids),
          skill_name = "qice",
          subcards = ids,
          cancelable = false,
        })
      end
    else
      local cards = table.filter(DIY.getCenterCards(Fk:currentRoom()),function (id)
        return Fk:getCardById(id).trueName == "slash"
      end)
      for _, v in ipairs({Player.HistoryPhase,Player.HistoryTurn,Player.HistoryRound,Player.HistoryGame}) do
        DIY.removeCenterCards(player,cards,v)
      end
      room:sendLog{
        type = "$RecastCenterArea",
        card = cards,
        arg = skel.name,
        from = player.id,
      }
      ids = room:getNCards(#cards)
      remove(player,ids,3)
      room:moveCardTo(ids,Card.DiscardPile,nil,fk.ReasonRecast,skel.name,nil,true,player)
      room:sendLog{
        type = "$PutToDiscard",
        card = ids,
        arg = #ids,
      }
    end
  end,
})

skel:addEffect(fk.CardShown, {
  can_refresh = function(self, event, target, player, data)
    if player:hasSkill(skel.name) then
      local parent = player.room.logic:getCurrentEvent():findParent(GameEvent.UseCard,nil,99)
      return parent and parent.data.card.skillName == skel.name
    end
  end,
  on_refresh = function (self, event, target, player, data)
    remove(player,data.cardIds,1)
  end,
})

skel:addEffect(fk.AfterCardsMove, {
  can_refresh = function(self, event, target, player, data)
    if player:hasSkill(skel.name) then
      for _, move in ipairs(data) do
        if move.moveReason == fk.ReasonDiscard then
          local parent = player.room.logic:getCurrentEvent():findParent(GameEvent.UseCard,nil,99)
          return parent and parent.data.card.skillName == skel.name
        end
      end
    end
  end,
  on_refresh = function (self, event, target, player, data)
    local ids = {}
    for _, move in ipairs(data) do
      for _, info in ipairs(move.moveInfo) do
        table.insert(ids,info.cardId)
      end
    end
    remove(player,ids,1)
  end,
})

skel:addEffect(fk.EventPhaseStart, {
  anim_type = "support",
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(skel.name) and player.phase == Player.Draw and not data.phase_end and player:isWounded()
    and DIY.getSwitchState(player,skel.name) == 2 and player:getMark(skel.name.."_wake") > 0
  end,
  on_cost = function (self, event, target, player, data)
    return player.room:askToSkillInvoke(player,{
      skill_name = "zaiqi",
    })
  end,
  on_use = function(self, event, target, player, data)
    change(player)
    local room = player.room
    data.phase_end = true
    local n = player:getLostHp()
    local cards = room:getNCards(n)
    player:addSkillUseHistory("zaiqi")
    remove(player,cards,2)
    room:moveCards{
      ids = cards,
      toArea = Card.Processing,
      moveReason = fk.ReasonJustMove,
      skillName = skel.name,
      proposer = player,
    }
    room:delay(math.min(n,4) * 400)
    local hearts, to_get = {}, {}
    for _, id in ipairs(cards) do
      if Fk:getCardById(id).suit == Card.Heart then
        table.insert(hearts, id)
      else
        table.insert(to_get, id)
      end
    end
    if #hearts > 0 then
      if player:isWounded() then
        room:recover({
          who = player,
          num = math.min(#hearts, player.maxHp - player.hp),
          recoverBy = player,
          skillName = "zaiqi",
        })
      end
      room:cleanProcessingArea(hearts)
    end
    if #to_get > 0 and not player.dead then
      room:obtainCard(player, to_get, true, fk.ReasonJustMove, player, "zaiqi")
    end
    room:cleanProcessingArea(cards)
  end,
})

skel:addAcquireEffect(function (self, player, is_start)
  player.room:addSkill("#CenterArea")
  DIY.setSwitchState(player, skel.name, 1, 3)
end)

skel:addLoseEffect(function (self, player, is_death)
  DIY.removeSwitchSkill(player, skel.name)
  player.room:setPlayerMark(player,skel.name.."_t",0) --实现方法是跳过而非移除
  player.room:setPlayerMark(player,skel.name.."_wake",0)
end)

return skel
